package at.fhooe.mc.msports;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import org.json.me.StringWriter;

import net.rim.device.api.system.AccelerometerData;
import net.rim.device.api.system.AccelerometerListener;
import net.rim.device.api.system.AccelerometerSensor;
import net.rim.device.api.system.AccelerometerSensor.Channel;
import net.rim.device.api.system.Application;

public class PedoManager implements AccelerometerListener{

	public Vector listeners = new Vector();
	private Channel rawDataChannel;
	public static final String FILE_URL = 
		"file:///store/Pedo.txt";
	private OutputStream out;
	boolean rising=false;
	private static int THRESHOLD=450;
	
	public void onData(AccelerometerData accData) {
		short x=accData.getLastXAcceleration();
		short y=accData.getLastYAcceleration();
		short z=accData.getLastZAcceleration();
		System.out.println("x:"+x+", y:"+y+", z:"+z);
		detectStep(accData);
	}
	public void detectStep(AccelerometerData accData){
		short x=accData.getLastXAcceleration();
		short y=accData.getLastYAcceleration();
		short z=accData.getLastZAcceleration();
		double a=Math.sqrt(x*x+y*y+z*z)-1000;
		
		if(a>THRESHOLD&&!rising){
			rising=true;
		}
		else if(a<=THRESHOLD&&rising){
			rising =false;
			for(int i=0;i<listeners.size();i++){
				((IPedometer)listeners.elementAt(i)).onStepDetected();
			}
		}
		
	}
	public void addListener(IPedometer listener){
		listeners.addElement(listener);
	}
	public void register(){
		rawDataChannel=AccelerometerSensor.openRawDataChannel( Application.getApplication());
		
		rawDataChannel.setAccelerometerListener(this);
		out=openFileForWriting(FILE_URL);
	}
	public void unregister(){
		rawDataChannel.close();
	}
	private OutputStream openFileForWriting(String filePath) {
	    try {
	        FileConnection fconn = (FileConnection) Connector.open(filePath);
	        // If no exception is thrown, then the URI is valid, but the file may or may not exist.
	        if (!fconn.exists()) {
	            fconn.create();  // create the file if it doesn't exist
	        }
	        return fconn.openOutputStream(fconn.fileSize());
	    } catch (IOException ioe) {
	        System.out.println("Could not open " + filePath + " for writing");
	    }
	    return null;
	}
}
